import 'dart:convert';
import 'dart:developer';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:im_base/im_base.dart';
import 'package:im_base/public/global/custom_bean.dart';
import 'package:im_base/public/global/im_keys.dart';
import 'package:im_base/public/pages/check_photo/view.dart';
import 'package:tencent_im_sdk_plugin/enum/message_elem_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

void showToast(String text, {int duration = 3}) {
  BotToast.showText(text: text, duration: Duration(seconds: duration));
}

void showSnackBar(String title, String message, {int dura = 3}) {
  Get.snackbar(title, message,
      isDismissible: true, duration: Duration(seconds: dura));
}

void toCheckPhoto(List<String> photos, int index) {
  log('toCheckPhoto---${index}');
  Get.to(() => CheckPhotoPage(), arguments: {'photos': photos, 'index': index});
}

///判断当前消息是否要展示未读数据
bool showUnread(V2TimMessage? lastMessage) {
  if (lastMessage == null) {
    return true;
  } else if (lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
    try {
      String data = (lastMessage.customElem?.data ?? '').isEmpty
          ? lastMessage.customElem?.extension ?? ''
          : lastMessage.customElem?.data ?? '';
      final bean = CustomBean.fromMap(jsonDecode(data));
      switch (bean.msg) {
        case IMKeys.TYPE_RECOMMEND: //群推荐
        case IMKeys.TYPE_CASE: //病历信息
          return true;
        default:
          return false;
      }
    } on Exception {
      return false;
    }
  } else {
    return true;
  }
}

///判断当前是否为视频问诊相关消息
bool showConversation(V2TimMessage? lastMessage) {
  if (lastMessage == null) {
    return true;
  } else if (lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
    try {
      String data = (lastMessage.customElem?.data ?? '').isEmpty
          ? lastMessage.customElem?.extension ?? ''
          : lastMessage.customElem?.data ?? '';
      final bean = CustomBean.fromMap(jsonDecode(data));
      switch (bean.msg) {
        case IMKeys.QUEUE_CANCEL: //群推荐
        case IMKeys.QUEUE_LIST: //病历信息
        case IMKeys.INQUIRY_IMAGES:
          return true;
        default:
          return false;
      }
    } on Exception {
      return false;
    }
  } else {
    return false;
  }
}

hideSoftKeyboard() {
  FocusScope.of(Get.context!).requestFocus(FocusNode());
}

///保存数据到内存
void writeIMData(String key, dynamic data) {
  StorageService.instance.writeData(key, data);
}

///从内存中读取数据,返回值可为null
T? readIMData<T>(String key) {
  StorageService.instance.readData(key);
}

///监听[key]对应的value数据变化
void watchIMData(String key, Function(dynamic) callBack) {
  StorageService.instance.watchData(key, callBack);
}
